<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #status="{ model, field }">
        <RadioGroup
          v-model:value="model[field]"
          option-type="button"
          button-style="solid"
          :options="sysStatusOptions"
        />
      </template>
      <template #imageUrl="{ model, field }">
        <CropperAvatar :uploadApi="uploadApi" :value="model[field]" @change="uploadAvatatAfter" />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './list.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { CropperAvatar } from '/@/components/Cropper';
  import { updateProductApi, addProductApi } from '/@/api/modules/business/product/list';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getDictEntryWithListByDictCodeApi } from '/@/api/modules/system/dictEntry';
  // import OSS from 'ali-oss';
  // import { getOssTokenApi } from '/@/api/modules/system/oss';
  import { uploadApi } from '/@/api/sys/upload';
  import { RadioGroup } from 'ant-design-vue';
  import { getParentProductCategoryTreeApi } from '/@/api/modules/business/product/category';
  export default defineComponent({
    name: 'ListDrawer',
    components: { BasicDrawer, BasicForm, CropperAvatar, RadioGroup },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const treeData = ref<any>([]);
      const rowId = ref();
      const checkedKeys = ref<any>([]);

      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 90,
        baseColProps: { span: 24 },
        schemas: formSchema,
        showActionButtonGroup: false,
      });
      const { createMessage } = useMessage();
      const sysStatusOptions = ref<any>([]);
      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        resetFields();
        setDrawerProps({ confirmLoading: false });

        isUpdate.value = !!data?.isUpdate;
        sysStatusOptions.value = await getDictEntryWithListByDictCodeApi({
          dictCode: 'sys_status',
        });
        const treeData = await getParentProductCategoryTreeApi();
        // await updateSchema([
        //   {
        //     field: 'status',
        //     componentProps: {
        //       options: sysStatusOptions,
        //     },
        //   },
        // ]);
        if (unref(isUpdate)) {
          rowId.value = data.record.id;
          setFieldsValue({
            ...data.record,
          });
        }

        updateSchema([
          {
            field: 'categoryId',
            componentProps: {
              options: treeData,
            },
          },
        ]);
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增物资' : '编辑物资'));
      // const img = 'https://markdownhexo.oss-cn-hangzhou.aliyuncs.com/20170331090953_zUcaS.thumb.1000_0.jpeg';

      // const client = new OSS({
      //   region: 'oss-cn-hangzhou',
      //   accessKeyId: 'LTAI5tQTdhUFySvfDqbVVNAq',
      //   accessKeySecret: 'aIH9NyobKw1I65rXFfZyjLhsj2Zphe',
      //   stsToken: 'yourSecurityToken',
      //   bucket: 'markdownhexo',
      // });
      // const uploadUrl = ref();
      // function uploadApi(
      //   params: UploadFileParams,
      //   onUploadProgress: (progressEvent: ProgressEvent) => void,
      // ) {
      //   getOssTokenApi().then((res) => {
      //     params.data = {
      //       ...params.data,
      //       key: res.dir + params.filename,
      //       OSSAccessKeyId: res.OSSAccessKeyId,
      //       policy: res.policy,
      //       signature: res.signature,
      //       dir: res.dir,
      //       expire: res.expire,
      //       file: params.file,
      //       success_action_status: '200',
      //     };
      //     uploadUrl.value = res.host.toString();
      //   });
      //   console.log('-------------params---------');
      //   console.log(params);
      //   // console.log('-------------onUploadProgress---------')
      //   // console.log(onUploadProgress)

      //   // console.log('-------------uploadUrl---------')
      //   // console.log(uploadUrl.value)
      //   return otherHttp.uploadFile(
      //     {
      //       url: uploadUrl.value,
      //       onUploadProgress,
      //     },
      //     params,
      //   );
      // }

      // function uploadApi(
      //   params: UploadFileParams,
      //   onUploadProgress: (progressEvent: ProgressEvent) => void,
      // ) {
      //   const uploadUrl = 'https://localhost:7242/api/Oss/UploadFile';
      //   return otherHttp.uploadFile(
      //     {
      //       url: uploadUrl,
      //       onUploadProgress,
      //     },
      //     params,
      //   );
      // }

      async function handleSubmit() {
        try {
          const values = await validate();
          setDrawerProps({ confirmLoading: true });
          !unref(isUpdate)
            ? await addProductApi(values)
            : await updateProductApi({ ...values, id: unref(rowId) });
          !unref(isUpdate) ? createMessage.success('新增成功') : createMessage.success('编辑成功');
          closeDrawer();
          emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }

      function uploadAvatatAfter({ data }) {
        setFieldsValue({
          imageUrl: data,
        });
      }

      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        treeData,
        checkedKeys,
        uploadApi: uploadApi as any,
        sysStatusOptions,
        uploadAvatatAfter,
      };
    },
  });
</script>
